<template>
  <div class="modal-from">
    <a-modal
      style="top: 50px;"
      :bodyStyle="{padding:'12px'}"
      :title="title"
      :width="1000"
      :maskClosable="true"
      :visible="visible"
      :destroyOnClose="true"
      @cancel="handleCancel"
    >
      <div slot="footer">
        <a-button @click="clickReset">重置</a-button>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary"  :loading="confirmLoading"  @click="submit">确定</a-button>
      </div>
      <!-- :title="!customer_response?'新顾客':'老顾客'" -->
      <a-card  :headStyle="{minHeight:0,padding:'3px 24px 10px'}"  :bordered="false" >
        <a-row :gutter="24">
          <a-col :md="6" :sm="24" >
            <a-form :form="form" layout="vertical" class="input-search">
              <a-form-item
                label="联系号码"
                :wrapperCol="wrapperCol"
                has-feedback
              >

                <!--  :disabled="disabled_search" -->
                <a-input-search
                  :loading="searchLoading"
                   @change="clearSpace"
                  @search="searchCustomer('tel')"
                  enter-button
                  :maxLength=11
                  ref="phoneInput"
                  placeholder="请输入联系号码"
                  type="tel"
                  v-decorator="['customerContact.contactContent',{rules: [{ required: true, message: '请输入联系号码！', },{validator:validatorPhone}]}]" />
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical" >
              <a-form-item
                label="联系方式"
                :wrapperCol="wrapperCol"
                has-feedback
              >
                <!-- :disabled="disabled" -->
                <a-select  style="width: 100%" v-decorator="['customerContact.contactType', {rules: [{ required: true, message: '请选择联系方式！' }]}]"  placeholder="请选择联系方式" >
                  <a-select-option v-for="(item,index) in CustomerConsult.contactDetails"  :key="index" :value="item.id" >{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical" class="input-search">
              <a-form-item
                label="客户姓名"
                :wrapperCol="wrapperCol"
                has-feedback
              >
              <!--  :disabled="disabled_search" 新增客户接待 姓名可修改 -->
                <a-input-search
                  ref="nameInput"
                   @change="clearSpace"
                  :loading="searchLoading"
                  @search="searchCustomer('name')"
                  enter-button              
                  placeholder="请输入客户姓名"
                  v-decorator="['customer.name',{rules: [{ required: true, message: '请输入客户姓名！' }]}]" />
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24" >
             <!-- :disabled="disabled_card" -->
            <a-form :form="form" layout="vertical" class="input-search">
              <a-form-item
                label="客户卡号"
                :wrapperCol="wrapperCol"
                has-feedback
              >
                <a-input-search
                  :loading="searchLoading"
                   @change="clearSpace"
                  @search="searchCustomer('cardNo')"
                  :maxLength=10
                  type="tel"
                  enter-button
                  v-decorator="['customer.cardNo']"
                  placeholder="请输入客户卡号"/>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical">
              <a-form-item
                label="信息来源"
                :wrapperCol="wrapperCol"
                has-feedback
              >
               <!-- :disabled="disabled_info_source" -->
                <a-cascader
                  allow-clear
                  expand-trigger="hover"
                  :show-search="{ filter }"
                 
                  :options="infoSource"
                  v-decorator="['customer.infoSource', {rules: [{ required: true, message: '请选择信息来源！' }]}]"
                  placeholder="请选择信息来源"/>
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical">
              <a-form-item label="区域来源" :wrapperCol="wrapperCol"  has-feedback>
                <!-- :disabled="disabled_area_source" -->
                <a-cascader
                  allow-clear
                  expand-trigger="hover"
                  :show-search="{ filter }"
                  
                  :options="area"
                  v-decorator="['customer.areaId', {rules: [{ required: true, message: '请选择区域来源！' }]}]"
                  placeholder="请选择区域" />
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical">
              <a-form-item
                label="性别"
                :wrapperCol="wrapperCol"
                has-feedback
              >
              <!-- :disabled="disabled_zixun" -->
                <a-select allow-clear  style="width: 100%" placeholder="请选择性别"  v-decorator="['customer.sex', {rules: [{ required:true, message: '请选择性别！' }]}]" >
                  <a-select-option  v-for="(item,index) in sex" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical">
              <a-form-item
                label="年龄"
                :wrapperCol="wrapperCol"
                has-feedback
              >
              <!--  :disabled="disabled_zixun" -->
                <a-input
                  @change="clearSpace"
                  placeholder="请填写年龄"
                  v-decorator="['customer.age',{validator: validatorAge}]" />
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>

         <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical">
              <a-form-item
                label="开发人员"
                :wrapperCol="wrapperCol"
                has-feedback
              >
                  <a-input
                  :disabled=true
                  v-decorator="['customer.developer_name']" />
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24" >
            <a-form :form="form" layout="vertical">
              <a-form-item label="所属咨询" :wrapperCol="wrapperCol"  has-feedback>
                <a-input          
                  :disabled=true
                  v-decorator="['customer.consult_man_name']" />
              </a-form-item>
            </a-form>
          </a-col>

          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical" class="input-search">
              <a-form-item
                label="介绍人"
                :wrapperCol="wrapperCol"
                has-feedback
              >
               <a-input  @change="clearSpace"  v-decorator="['customer.jsr',]" allow-clear placeholder="介绍人" />
              </a-form-item>
            </a-form>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form :form="form" layout="vertical" class="input-search">
              <a-form-item label="介绍人卡号" :wrapperCol="wrapperCol"  has-feedback>
                <a-input-search class="myButton" :loading="searchLoading"
                            @search="searchUser"
                            enter-button 
                            @change="clearSpace"
                            v-decorator="['customer.jsrkh',]"
                            placeholder="请输入介绍人卡号" />
              </a-form-item>
            </a-form>
          </a-col>
          
        </a-row>


        <a-row :gutter="24">
           <a-col :md="24" :sm="24" >
            <a-form  layout="vertical" class="input-search">
              <a-form-item
                 style="margin-bottom:0px"
                 v-for="(item,index) in last_info" :key="index"
                 class="myAlert"
               >
                <a-alert 
                   style="padding-left:10px;padding-right:0;padding-top:8px;padding-bottom:8px;"
                  :description=item.msg
                  :type=item.type
                  :showIcon=false
                  :closable=false
                  :banner=false
                />
              </a-form-item>
            </a-form>
           </a-col>
        </a-row>

        
      </a-card>
      <a-card :headStyle="{minHeight:0,padding:'3px 24px 10px'}" title="分诊资料" :bordered="false" >
        <div class="table-page-search-wrapper">
          <a-row :gutter="24" type="flex" align="middle" style="margin-top: 0px;">
            <a-col :span="12" >
               <!-- :disabled="disabled_zixun" -->
              <a-form :form="form" layout="inline" >
                <a-form-item
                  label="客户诉求"
                  :wrapperCol="wrapperCol"
                  has-feedback>
                  <a-cascader
                    allow-clear                 
                    :options="ConsultationAppeal"
                    expand-trigger="hover"
                    :show-search="{ filter }"
                    v-decorator="['quoteItemList', {rules: [{ required: true, message: '请选择项目！' }]}]"
                    placeholder="选择，可搜索"
                  />
                </a-form-item>
              </a-form>
            </a-col>
            <a-col :span="12"  >
              <a-form :form="form"  class="radio-group" layout="inline" >
                <a-form-item label="是否复查" labelAlign="left">
                  <!-- :disabled="disabledReview" -->
                  <a-radio-group   v-decorator="['isReview', {initialValue:0,rules: [{ required: true, message: '请选择！' }]}]" >
                    <a-radio :value="1">是</a-radio>
                    <a-radio :value="0">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
        </div>
        <!--用户模块弹出窗，待优化抽离-->
        <a-modal
          title="双击选择客户"
          :footer="null"
          style="margin-top: 55px;"
          :width="800"
          :visible="visibleTable"
          :confirmLoading="confirmLoading"
          @cancel="visibleTable=false"
        >
          <a-table
            :alert="true"
            :columns="columns"
            :data-source="customerDataTable"
            :loading="customerTableLoading"
            :pagination="pagination"
            :rowKey="(record,index)=>index"
            @change="handleTableChange"
            :customRow="click"
          >
          </a-table>
        </a-modal>
      </a-card>
  </a-modal>
  </div>
</template>

<script>
import {
  getConsulationListByCardNo,
  getConsulationListByName,
  getConsulationListByTel,
  getConsultationAppeal,
  getClientDemandName
} from '@/api/modular/main/customer/customerConsultation'
import {getCustomerConsult, getInfoSource} from '@/api/customer/customer'
import {getInfo, receiveAdd} from '@/api/modular/main/customer/customerTriage'
import moment from 'moment'
import areaObj from '@/assets/flowable/js/areaData'
import infoSourceObj from '@/assets/flowable/js/infoSource'


export default {
  data(){
    return{
      // 查询参数
      queryParam: {
        pageNum: 1,//第几页
        pageSize: 10,//每页中显示数据的条数
        // searchValue: '',
      },
      customer_response:'',
      value: [],
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      title:"新增客户接待",
      sex:[{'id':'0','name':'男'},{'id':'1','name':'女'}],
      area: areaObj.areaData,//区域
      infoSource: [],//消息来源
      CustomerConsult: { //客户咨询下拉系列
        incomingState : [],//来院状态
        consultationStatus : [],//咨询状态
        admissionStatus  : [],//接诊状态
        comeHosStatus : [],
        //来院意向
        consultTools : [],//咨询工具
        contactDetails : [],//联系方式
      },
      //客户诉求列表
      ConsultationAppeal : [],
      contact_content:'', //联系
      disabled:false,
      disabled_search:false,
      disabled_name:false,
      disabled_card:false,
      disabled_tel:false,
      disabled_age:true,
      disabled_zixun:true,
      disabled_info_source:true,
      disabled_area_source:true,
      visible: false,
      visibleTable: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      required_tel:true,
      customerTableLoading:false,
      pagination: {
        current: 1,//当前页
        pageSize: 10,//当前页数
        total: 0,//总条数
        showSizeChanger: true,
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30'],//这里注意只能是字符串，不能是数字
        showTotal: total => `共有 ${ total} 条数据`,//分页中显示总的数据
      },
      customerDataTable:[],
      columns: [
        { title: '序号', customRender: (text, record, index)=>(this.pagination.current-1)*this.pagination.pageSize+(index+1) },
        { title: '姓名', dataIndex: 'name' },
        { title: '卡号', dataIndex: 'cardNo' },
        { title: '开发员', dataIndex: 'developer', customRender:age=>age?age:'无' },
        { title: '咨询师', dataIndex:'consultMan',customRender:consultMan=> consultMan?consultMan:'无'},
        { title: '登记时间', dataIndex: 'recordDate', }
      ],
      searchLoading:false,
      searchLoading1:false,
      jsrCustomrId:"",
      last_info:[]
    }
  },

  created() {
    this.getInfoSource()
    this.getCustomerConsult()
    this.getConsultationAppeal()
  },
  watch:{
    customer_response(newV,oldV){
      // console.log('newV' ,newV)
      if(newV !== ""){          
         if(newV.type == 0){
              this.title='新增客户接待 (新顾客)'
         }
          if(newV.type == 1){
              this.title='新增客户接待 (老顾客)'         
         }
      }else{
        this.title='新增客户接待'
      }
    },  
  },
  computed:{
    disabledReview(){
      if(this.customer_response.type === 0){
        return true
      }
      return this.customer_response?false:true
    }
  },
  methods:{
    clearSpace(e){
      e.target.value=e.target.value.replace(/\s+/g,'')
    },
    moment,
    filter(inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    },
    clickReset(){
      this.visible = true
      this.disabled_search=false
      this.disabled_age=true
      this.last_info=[]
      this.customer_response=''
      this.form.resetFields()
      this.$nextTick(()=>{
        this.$refs.phoneInput.focus()
      })
    },
    //搜索介绍人
    searchUser(){
      let jsrkh =this.form.getFieldValue('customer.jsrkh')
      this.searchLoading1 = true   
      if (jsrkh) {
          getConsulationListByCardNo(jsrkh).then(res => {
              this.searchLoading1 = false
              if(res.rows && res.rows.length >0){
                   this.form.setFieldsValue({
                   'customer.jsr': res.rows[0].name,   
                   })
                   this.jsrCustomrId= res.rows[0].customerId
              }else{
                  this.form.setFieldsValue({
                   'customer.jsr': undefined,            
                   })
                  this.jsrCustomrId=undefined
                this.$message.info("搜索不到此介绍人！")
              }    
          })
      } else {
          this.jsrCustomrId=undefined
          this.searchLoading1 = false
          this.$message.info("介绍人卡号为空")
      }
    },
   
    //信息来源
    getInfoSource(){
      getInfoSource().then(res => {
        this.infoSource = res
      })
    },
    //下拉接口集合
    getCustomerConsult(){
      getCustomerConsult().then(res => {
        this.CustomerConsult = res        
      })
    },
    getConsultationAppeal(){
      getClientDemandName().then(res => {
        this.ConsultationAppeal = res.rows
      })

    },
    /**
     判断渲染表格
     * */
    resToRender(res){
      if(res.code==200){
        //搜索不到用户
        if(res.rows.length<=0){
          this.title="新增客户接待"
          this.$message.info({
            content:'该客户不存在',
            duration:.5,
          })
          this.last_info=[]

          this.disabled=false       
          this.disabled_age=false
        }else if(res.rows.length==1){
          //搜索到一条数据，直接渲染，需要选择点击
          this.getCustomerInfoAndRender({id:res.rows[0].customerId,tel:res.rows[0].contactContent})
         

        }else{
          //搜索到用户数据两条以上
          this.visibleTable=true
          this.customerDataTable=res.rows
        }
      }
    },
    /**
     查询客户
     * */
    searchCustomer(type){
      this.disabled=true
      const name =this.form.getFieldValue('customer.name');
      const cardNo =this.form.getFieldValue('customer.cardNo');
      const tel =this.form.getFieldValue('customerContact.contactContent');
      this.searchLoading = true
      if(type=='name'){
        if(!name){
          this.form.setFields({
            [`customer.name`]:{ errors:[{ message:'请填写姓名！'}], }
          })
          this.searchLoading = false
          return
        }
        var reg = new RegExp("^[A-Za-z0-9\u4e00-\u9fa5]+$")

        if(!reg.test(name)){
           this.$message.info('格式错误,名称为中英文数字！')
           this.searchLoading = false
           return
        }


        this.form.resetFields()
        this.form.setFieldsValue({
          'customer.name':  name.replace(/\s+/g,""),
        })
        this.required_tel=false
        getConsulationListByName(name).then(res=>{
          this.resToRender(res)
          this.confirmLoading = false
          this.searchLoading = false
        })
        return
      }

      if(type=='cardNo'){
        if(!cardNo){
          this.form.setFields({
            [`customer.cardNo`]:{ errors:[{ message:'请填写卡号！'}], }
          })
          this.searchLoading = false
          return
        }
        
        var reg =/^[0-9]*$/
        if(!reg.test(cardNo)){
            this.$message.info('格式错误,卡号为数字！')
           this.searchLoading = false
           return
        }
  

        this.form.resetFields()
        this.form.setFieldsValue({
          'customer.cardNo':  cardNo.replace(/\s+/g,""),
        })
        getConsulationListByCardNo(cardNo).then(res=>{
          this.resToRender(res)
          this.confirmLoading = false
          
          this.searchLoading = false
        })
        return
      }

      if(type=='tel'){
        if(!tel){
          this.form.setFields({
            [`customerContact.contactContent`]:{ errors:[{ message:'请填写联系号码！'}], }
          })
          this.searchLoading = false
          return
        }
        
         var reg =/^[1-9]\d*$|^0$/
        if(!reg.test(tel)){
           this.$message.info('格式错误,电话为数字！')
           this.searchLoading = false
           return
        }

        this.form.resetFields()
        this.form.setFieldsValue({
          'customerContact.contactContent':  tel.replace(/\s+/g,""),
        })
        getConsulationListByTel(tel).then(res=>{
          console.log('查询结果',res)
          this.resToRender(res)
          this.confirmLoading = false
          this.searchLoading = false
        })
      }
    },
    // 初始化方法
    add () {
      this.visible = true
      this.last_info=[]
      this.disabled_search=false
      this.disabled_age=true
      this.customer_response=''
      this.form.resetFields()
      this.$nextTick(()=>{
        this.$refs.phoneInput.focus()      
        this.form.setFieldsValue({
          'customerContact.contactType':this.CustomerConsult.contactDetails[0].id,
        })
      })
      // this.getCustomerFeedback()
    },
    /**
     表单校验手机号格式
     * */
    validatorPhone (rule, value, callback) {
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!reg.test(value)) {
        callback('11位')
      }
      callback()
    },
    
    submit(){
      const { form: { validateFields } } = this
      if(!this.confirmLoading){
          this.confirmLoading = true

           validateFields((errors, values) => {
        if (errors) {
          console.log('表单校验未通过111')
          this.confirmLoading=false
          return
        }
        if(values.customer.infoSource&&values.customer.infoSource?.length>0){
          values.customer.infoSource=values.customer.infoSource[1]
        }else{
          values.customer.infoSource=this.customer_response.info_source
        }

        if( values.customer.areaId instanceof Array ){
          const len = values.customer.areaId.length
          values.customer.areaId=values.customer.areaId[len-1]
          let address = areaObj.getAddress(values.customer.areaId)
          let str=''
          address.forEach(item=>{
            str=str+item
          })
          values.customer.area=str
         
          

        }else if(typeof (values.customer.areaId) == 'undefined'){
          values.customer.areaId = null
          values.customer.area= null
        } else{
          values.customer.areaId=this.customer_response.area_id
          let address = areaObj.getAddress(values.customer.areaId)
          let str=''
          address.forEach(item=>{
            str=str+item
          })
          values.customer.area=str
           
       
        }

        if(values.customer.sex){
          if(values.customer.sex==='男'){
            values.customer.sex=0
          }
          if(values.customer.sex==='女'){
            values.customer.sex=1
          }
        }

        // 介绍人id
        if(this.jsrCustomrId){
           values.customer.introducerId=this.jsrCustomrId
        }else{
          delete values.customer.introducerId
        }

        //老顾客
        if(this.customer_response) {
          values.customer.customerId = this.customer_response.customerId
        }
        
        // 年龄
        if(!values.customer.age){
          delete values.customer.age
        }
        // 卡号
        if(!values.customer.cardNo){
          delete values.customer.cardNo
        }

        let params = JSON.parse(JSON.stringify(values))
        params.quoteItemList = [params.quoteItemList[1]]
        // params.quoteItemList.splice(-1,1)
        console.log('表单校验通过222',params)
        receiveAdd(params).then(res =>{
          console.log('提交结果为',res)
          if(res.code==200){
            this.$message.success({
              content:'增加成功',
              duration:0.5,
              onClose:()=>{
                this.confirmLoading = false
                this.visible=false
                this.$parent.$refs.table.refresh()
              }
            })
          }else{
            this.$message.info({
              content:res.message,
              duration:0.5
            })
            this.confirmLoading = false
          }
        })
      })
      } 
    },
    //分页动作监听
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
    },
    handleCancel () {
      this.form.resetFields()
      this.visible = false
      // 清理子表单中数据
      // 清理时间
    },
    // 表格行点击事件
    click(record, index){
      return {
        on: {
          dblclick:()=>{
            const customerId = record.customerId
            const contactContent = record.contactContent
            this.getCustomerInfoAndRender({ id:customerId,tel:contactContent })
          }
        }
      }
    },
    /**
     表单校验年龄
     * */
    validatorAge (rule, value, callback) {
      if(!value){
        callback()
      }
      if(value>0&&value<100){
        callback()
      }
      callback('年龄必须为1-99')
    },
    /**
     请求用户资料数据并且渲染页面
     * */
    getCustomerInfoAndRender(params){
      const tel =this.form.getFieldValue('customerContact.contactContent')
      getInfo(params).then(res=>{
        if(res.code==200){
          const customerInfo = res.data      
          console.log('渲染的数据信息为',customerInfo)
          this.customer_response = customerInfo
          this.form.setFieldsValue({
            'customer.age': customerInfo.age,
            'customer.name': customerInfo.name,
            'customer.cardNo': customerInfo.card_no,
            'customer.areaId': customerInfo.area_id==0?undefined: areaObj.getAreaId(customerInfo.area_id),
            'customer.infoSource':customerInfo.info_source===0?undefined: infoSourceObj.getinfoSourceId( this.infoSource,customerInfo.info_source),
            'customer.sex':customerInfo.sex==1?'女':'男',
            'customer.developer_name':customerInfo.developer_name?customerInfo.developer_name:'暂无',
            'customer.consult_man_name':customerInfo.consult_man_name?customerInfo.consult_man_name:'暂无',
            // 'customerContact.contactType':customerInfo.contact_type,
            'customerContact.contactType': this.CustomerConsult.contactDetails.filter(item =>{ return item.id == customerInfo.contact_type}).length > 0 ? customerInfo.contact_type :undefined ,
            'customerContact.contactContent':customerInfo.contact_content,
            'quoteItemList':  customerInfo.quoteItemList ||[]
          })
          this.visibleTable=false
          if(!customerInfo.age||customerInfo.age<0||customerInfo.age>99){
            this.disabled_age=false
          }
          this.last_info= res.data.last_info
        }else{
          this.$message.info({
            content:res.message,
            duration:0.5,
            onClose:()=>{
              this.visibleTable=false
            }
          })
        }
      })
    },

  }
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-head-title{
  font-weight: bold;
  padding: 0;
}
/deep/ .ant-page-header-heading-title{
  font-weight: normal;
  font-size: 16px;
}
/deep/ .ant-card-body {
  padding: 24px 12px 0 ;
}
/deep/ .ant-form-item-control-wrapper{
  width: 100%;
}
.input-search .has-success.has-feedback .ant-form-item-children-icon{
  top: 60%;
  right: 50px !important;
}
/deep/ .myButton Button{
  background-color: rgb(218, 163, 27);
  border:none
}

/deep/ .ant-form-item{
  margin-bottom: 16px;
}

/* /deep/ .myAlert{
  .ant-alert-with-description.ant-alert-no-icon{
     background-color: red;
  }

} */
</style>